"use client";

import { Dispatch, useEffect, useState, type ChangeEvent } from "react";
import { PulseLoader } from "react-spinners";

export default function Apply() {
  const [text, setText] = useState<string>("");
  const [isError, setIsError] = useState<boolean>(false);
  const [isOpen, setIsOpen] = useState<boolean>(false);

  const handleChange = (e:ChangeEvent<HTMLInputElement>) => {
    setText(e.target.value);
    setIsError(false);
  };

  const handleClick = () => {
    if (text) {
      setIsOpen(true);
    } else {
      setIsError(true);
    }
  };

  return (
    <div className="p-[20px] max-w-[680px] m-auto">
      <h3 className="text-center font-bold text-[18px]">
        Request to clear data
      </h3>
      <input
        value={text}
        onChange={handleChange}
        className={`block w-full h-[40px] border border-solid border-[#ddd] mt-[130px] text-[16px] outline-none text-center rounded-[5px] ${
          isError ? "placeholder:text-[red]" : ""
        }`}
        placeholder="Please enter your account"
      />
      <button
        onClick={handleClick}
        className="block w-full mt-[20px] px-[8px] py-[15px] bg-white border border-solid border-[#ddd] rounded-[5px]"
      >
        Clear all data from my account
      </button>
      <p className="text-center mt-[20px] text-[red]">
        Please choose carefully, your account will become invalid after deleting
        data
      </p>
      {isOpen && <Modal onClose={(_) => setIsOpen(false)} />}
    </div>
  );
}

const Modal = ({ onClose }:{onClose: Dispatch<void>}) => {
  const [isLoading, setIsLoading] = useState(true);
  useEffect(() => {
    setTimeout(() => {
      setIsLoading(false);
    }, 500);
  }, []);

  return (
    <div>
      <div
        className="fixed z-[1] left-0 right-0 top-0 bottom-0 bg-[rgba(0,0,0,0.199)] flex items-center justify-center"
        onClick={() => onClose()}
      >
        {isLoading ? (
          <PulseLoader color="black" />
        ) : (
          <div
            className="w-[90%] bg-white px-[30px] py-[20px] rounded-[5px]"
            onClick={(e) => e.stopPropagation()}
          >
            <h3 className="text-center font-bold text-[18px]">
              Successful application
            </h3>
            <p className="text-center my-[30px]">
              We will clear the data for you after review
            </p>
            <button
              onClick={() => onClose()}
              className="block px-[40px] py-[8px] bg-white border border-solid border-[#ddd] rounded-[5px] text-[16px] m-auto"
            >
              OK
            </button>
          </div>
        )}
      </div>
    </div>
  );
};
